#ifndef __APP_TASK_H__
#define __APP_TASK_H__

#include "common_util.h"

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define SCHEDU_LIST_MAXSIZE 20 /* 调度表最大数量 */

typedef struct
{
    void (*schedu_func)(void);
    uint32_t period;
    bool     enable; /* 是否启用 */
    bool     reuse;  /* 是否周期调度 */
    uint32_t count;  /* 计数值 */
    uint32_t last_run_tick;
} scheduler_t;

extern scheduler_t   schedu_list[SCHEDU_LIST_MAXSIZE];
extern const uint8_t schedu_list_size;

/**
 * @brief 调度器, 放入main函数中循环调用
 *
 */
__attribute__((always_inline)) inline static void app_task_scheduler_handle(scheduler_t *schedu_list,
                                                                            uint8_t      list_size)
{
    scheduler_t *schedu_obj = NULL;

    for (int i = 0; i < SCHEDU_LIST_MAXSIZE; ++i) {
        schedu_obj = schedu_list + i;
        if ((schedu_obj->schedu_func) != NULL) {
            if (schedu_obj->enable == true) {
                if ((schedu_obj->count + schedu_obj->period <= common_util_get_tick()) ||
                    (schedu_obj->count == 0)) {
                    schedu_obj->count = common_util_get_tick();
                    schedu_obj->schedu_func();
                    if (!(schedu_obj->reuse)) {
                        schedu_obj->enable = false;
                    }
                }
            }
        }
        else {
            return;
        }
    }
}

void app_task_init(void);

#endif
